<template>
  <div v-if="isDetail">
    <member-detail :userId="userId"></member-detail>
  </div>
  <div class="app-container" v-else>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      v-show="showSearch"
      label-width="68px"
    >
      <el-row :gutter="20">
        <el-col :span="4" :offset="0">
          <el-form-item label="会员ID" prop="sysUserid">
            <el-input
              v-model="queryParams.sysUserid"
              placeholder="请输入会员ID"
              clearable
              size="mini"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4" :offset="0">
          <el-form-item label="会员名称" prop="nickName">
            <el-input
              v-model="queryParams.nickName"
              placeholder="请输入会员昵称"
              clearable
              size="mini"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="0">
          <el-form-item label="注册时间" prop="createTime">
            <el-date-picker
              v-model="createTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="mini"
              @change="searchTimeHandler"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="4" :offset="0">
          <el-form-item label="会员等级" prop="memberLevel">
            <el-select
              v-model="queryParams.memberLevel"
              placeholder="请选择会员等级"
              clearable
              size="mini"
            >
              <el-option
                v-for="item in levelList"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="0">
          <el-form-item label="余额" prop="remainingSumStart">
            <div style="display: flex">
              <div>
                <el-input
                  v-model="queryParams.remainingSumStart"
                  size="mini"
                  clearable
                >
                  <span slot="suffix">元</span>
                </el-input>
              </div>
              <div style="margin: 0 10px">-</div>
              <div>
                <el-input
                  v-model="queryParams.remainingSumEnd"
                  size="mini"
                  clearable
                >
                  <span slot="suffix">元</span>
                </el-input>
              </div>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="0">
          <el-form-item label="积分" prop="creditScoreStart">
            <div style="display: flex">
              <div>
                <el-input
                  v-model="queryParams.creditScoreStart"
                  size="mini"
                  clearable
                >
                  <span slot="suffix">分</span>
                </el-input>
              </div>
              <div style="margin: 0 10px">-</div>
              <div>
                <el-input
                  v-model="queryParams.creditScoreEnd"
                  size="mini"
                  clearable
                >
                  <span slot="suffix">分</span>
                </el-input>
              </div>
            </div>
          </el-form-item>
        </el-col>

        <el-col :span="6" :offset="0">
          <el-form-item label="" label-width="0">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:rule:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:rule:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:rule:remove']">删除</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:rule:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="ruleList"
      @selection-change="handleSelectionChange"
      class="f-size"
    >
      <el-table-column
        label="会员id"
        align="center"
        prop="sysUserid"
        :width="100"
      />
      <el-table-column label="会员" prop="sysUserid" :min-width="160">
        <template slot-scope="{ row }">
          <div class="user">
            <div class="user-img">
              <image-preview
                :src="row.avatar"
                width="50px"
                height="50px"
              ></image-preview>
            </div>
            <div class="user-info">
              <div>{{ row.nickName }}</div>
              <div>渠道：小程序</div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="手机号"
        align="center"
        prop="phonenumber"
        :width="110"
      />
      <el-table-column
        label=" 会员等级"
        align="center"
        prop="memberLevel"
        :min-width="70"
      >
        <template slot-scope="{ row }">
          {{ forrmatterEnmu(levelList, row.memberLevel) }}
        </template>
      </el-table-column>
      <el-table-column
        label="上次消费时间"
        align="center"
        prop="orderCreateTime"
        :min-width="150"
      />
      <el-table-column
        label="余额/销售利润"
        prop="remainingSum"
        :min-width="170"
      >
        <template slot-scope="{ row }">
          <div>余额：{{ row.remainingSum }}</div>
          <div>销售利润：{{ row.profit }}</div>
        </template>
      </el-table-column>
      <el-table-column
        label="积分"
        align="center"
        prop="creditScore"
        :min-width="90"
      />
      <el-table-column
        label="代理等级"
        align="center"
        prop="memberAgencyLevel"
        :width="120"
      >
        <template slot-scope="{ row }">
          {{ forrmatterEnmu(DictData.levelList, row.memberAgencyLevel) }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="用户id" align="center" prop="sysUserid" /> -->
      <!-- <el-table-column label="类型" align="center" prop="type" />
      <el-table-column label="升级到此等级的人员数量" align="center" prop="upgradeUserCount" /> -->
      <el-table-column
        label="会员注册时间"
        align="center"
        prop="registerCreateTime"
        :min-width="150"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        :width="70"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="searchHandler(scope.row)"
            v-hasPermi="['system:rule:edit']"
            >查看</el-button
          >
          <!-- <el-button size="mini" type="text" @click="handleDelete(scope.row)"
            v-hasPermi="['system:rule:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户会员对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="16" :offset="0">
            <el-form-item label="会员昵称" prop="nikeName">
              <el-input v-model="form.nikeName" placeholder="请输入会员昵称" />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="会员等级" prop="memberLevel">
              <el-select
                v-model="form.memberLevel"
                placeholder="请选择会员等级"
                clearable
                @change="memberLevelChange"
              >
                <el-option
                  v-for="item in levelList"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16" :offset="0">
            <el-form-item label="代理等级" prop="memberAgencyLevel">
              <el-select
                v-model="form.memberAgencyLevel"
                placeholder="请选择代理等级"
                clearable
                @change="memberAgencyLevelChange"
              >
                <el-option
                  v-for="item in DictData.memberLevelList"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16" :offset="0">
            <!-- <el-form-item label="上级推荐人" prop="parentId">
              <el-input
                v-model="form.parentId"
                placeholder="请输入上级推荐人"
              />
            </el-form-item> -->
            <el-form-item label="上级推荐人" prop="parentId">
              <div style="display: flex; align-items: center">
                <image-preview
                  :src="referrer.avatar"
                  height="50px"
                  width="50px"
                ></image-preview>
                <div style="margin: 0 10px 0">
                  <div>{{ referrer.nickName }}</div>
                  <div>ID：{{ referrer.sysUserid }}</div>
                </div>
                <el-button size="mini" type="text" @click="handleReferrer"
                  >选择上级推荐人</el-button
                >
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="16" :offset="0">
            <el-form-item label="手机号" prop="phonenumber">
              <el-input v-model="form.phonenumber" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="16" :offset="0">
            <el-form-item label="备注信息" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 推荐人弹窗 -->
    <ChooseReferrer
      :show="referrerShow"
      @confirm="referrerConfrim"
      @close="referrerShow = false"
    />
  </div>
</template>

<script>
import {
  listRule,
  getRule,
  delRule,
  addRule,
  updateRule,
} from "@/api/system/member/rule";
import { forrmatterEnmu } from "@/utils/index";
import MemberDetail from "./memberDetail.vue";
import ChooseReferrer from "./components/chooseReferrer.vue";
import { watch } from "less";

export default {
  name: "Rule",
  components: { MemberDetail, ChooseReferrer },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户会员表格数据
      ruleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否推荐人弹窗
      referrerShow: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sysUserid: null,
        memberName: null,
        memberLevel: "",
        userCreateStartTime: null,
        userCreateSEndTime: null,
        remainingSumStart: null,
        remainingSumEnd: null,
        creditScoreStart: null,
        creditScoreEnd: null,
        createTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // memberLevel: [
        //   { required: true, message: '会员等级不能为空', trigger: 'blur' },
        // ],
        nikeName: [
          { required: true, message: "会员名称不能为空", trigger: "blur" },
        ],
        phonenumber: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
        ],
        parentId: [
          { required: true, message: "选择上级推荐人", trigger: "blur" },
        ],
      },
      // 会员级别
      levelList: [
        {
          value: "",
          name: "全部",
        },
        {
          value: 0,
          name: "普通用户",
        },
        {
          value: 1,
          name: "vip",
        },
        {
          value: 2,
          name: "svip",
        },
        {
          value: 3,
          name: "共享店主",
        },
        {
          value: 4,
          name: "联创",
        },
        {
          value: 5,
          name: "区域运营中心",
        },
        {
          value: 6,
          name: "总裁",
        },
      ],
      baseURL: process.env.VUE_APP_BASE_API,
      isDetail: false,
      userId: null,
      createTime: null,
      referrer: {
        avatar: null,
        sysUserid: "",
        nickName: null,
      },
    };
  },
  created() {
    this.getList();

    if (this.$route.query) {
      this.isDetail = this.$route.query.value;
    } else {
      this.isDetail = false;
    }
  },
  watch: {
    // 监听路由对象中的params或query属性
    "$route.query": {
      immediate: true,
      handler() {
        if (this.$route.query) {
          this.isDetail = this.$route.query.value;
        } else {
          this.isDetail = false;
        }
      },
    },
  },
  methods: {
    forrmatterEnmu,
    /** 查询用户会员列表 */
    getList() {
      this.loading = true;
      listRule(this.queryParams).then((response) => {
        this.ruleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        memberName: null,
        memberLevel: null,
        memberAgencyLevel: null,
        memberAgencyLevelName: null,
        sysUserid: null,
        type: null,
        giftpackId: null,
        upgradeUserCount: null,
        state: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        parentId: null,
      };
      this.resetForm("form");
    },
    memberLevelChange(v) {
      let newList = this.levelList.filter((item) => item.value == v);
      this.form.memberName = newList[0]?.name;
    },
    memberAgencyLevelChange(v) {
      let newList = this.DictData.levelList.filter((item) => item.value == v);
      this.form.memberAgencyLevelName = newList[0]?.name;
    },
    handleReferrer() {
      this.referrerShow = true;
    },
    referrerConfrim(e) {
      this.referrer = e;
      this.$refs.form.clearValidate("parentId");
      this.referrerShow = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.createTime = null;
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        sysUserid: null,
        memberName: null,
        memberLevel: null,
        userCreateStartTime: null,
        userCreateSEndTime: null,
        remainingSumStart: null,
        remainingSumEnd: null,
        creditScoreStart: null,
        creditScoreEnd: null,
      };
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.referrer = {
        avatar: null,
        sysUserid: "",
        nickName: null,
      };
      this.title = "添加用户会员";
    },
    /**查看按钮操作 */
    searchHandler(row) {
      this.$router.push(
        `/member/list/index?value=${true}&userId=${row.sysUserid}`
      );
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getRule(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用户会员";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.parentId = this.referrer.sysUserid;

      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateRule(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRule(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除用户会员编号为"' + ids + '"的数据项？')
        .then(function () {
          return delRule(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/rule/export",
        {
          ...this.queryParams,
        },
        `rule_${new Date().getTime()}.xlsx`
      );
    },
    searchTimeHandler(v) {
      this.queryParams.userCreateStartTime = this.$dayjs(v[0]).format(
        "YYYY-MM-DD hh:mm:ss"
      );
      this.queryParams.userCreateSEndTime = this.$dayjs(v[1]).format(
        "YYYY-MM-DD hh:mm:ss"
      );
    },
  },
};
</script>

<style lang="less" scoped>
.f-size {
  font-size: 12px;
}
</style>
